<?php

require Yii::getPathOfAlias('application.project_common.vendor.submail') . '/SUBMAILAutoload.php';

/**
 *
 * @author lovebing Create On Oct 19, 2015
 */
class Mailer extends MAILSend {

    protected $errcode = 0;
    protected $errmsg = '';

    public function __construct($wid=0) {
        $configs = Yii::app()->params['submail'];
        if($wid)
        {
            $seting=  SystemSubmail::findActiveModel($wid);
            if($seting)
            {
                $configs['appid']=$seting->appid;
                $configs['appkey']=$seting->appkey;
                $configs['sender']['name']=$seting->sender_name;
                $configs['sender']['address']=$seting->sender_address;
            }
        }
        parent::__construct($configs);
        $this->SetSender($this->getSenderAddress(), $this->getSenderName());
        $this->setAsynchronous(false);
    }

    public function getSenderAddress() {
        return Yii::app()->params['submail']['sender']['address'];
    }

    public function getSenderName() {
        return Yii::app()->params['submail']['sender']['name'];
    }

    public function send() {
        $res = parent::send();
        if (!$res) {
            $this->setError('发送失败');
            return false;
        }
        if (!isset($res['status'])) {
            $this->setError('不期望的返回结果');
            return false;
        }
        if ($res['status'] == 'success') {
            return true;
        }

        $this->setError($res['msg'], $res['code']);

        return false;
    }

    /**
     * 
     * @param array $to
     */
    public function setToArray(array $to) {
        $list = array();
        foreach ($to as $name => $address) {
            $item = array(
                'address' => $address,
                'name' => is_numeric($name) ? '' : $name
            );
            $list[] = $item;
        }
        $this->To = $list;
    }

    /**
     * 
     * @param array $cc
     */
    public function setCcArray(array $cc) {
        $list = array();
        foreach ($cc as $name => $address) {
            $item = array(
                'address' => $address,
                'name' => is_numeric($name) ? '' : $name
            );
            $list[] = $item;
        }
        $this->Cc = $list;
    }

    /**
     * 
     * @param array $bcc
     */
    public function setBccArray(array $bcc) {
        $list = array();
        foreach ($bcc as $name => $address) {
            $item = array(
                'address' => $address,
                'name' => is_numeric($name) ? '' : $name
            );
            $list[] = $item;
        }
        $this->Bcc = $list;
    }

    public function setError($msg, $code = 1) {
        $this->errcode = $code;
        $this->errmsg = $msg;
    }

    public function getErrorCode() {
        return $this->errcode;
    }

    public function getErrorMessage() {
        return $this->errmsg;
    }

}
